package com.mars.module.tool.utils;

import org.apache.http.HttpHost;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.nio.charset.StandardCharsets;
import java.sql.*;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 功能描述
 *
 * @author 程序员Mars
 * @version 1.0
 * @date 2024-01-18 10:50:29
 */
public class LogReceiver {


    private static final int BUFFER_SIZE = 65507; // 最大UDP数据包大小
    private static final int LOG_PORT = 514; // UDP日志接收端口

    private DatagramSocket socket;
//    private RestHighLevelClient esClient;
    private Connection mysqlConnection;
    private Map<String, Pattern> logPatterns;

    public LogReceiver() throws IOException {
        socket = new DatagramSocket(LOG_PORT);
//        esClient = new RestHighLevelClient(RestClient.builder(new HttpHost("localhost", 9200, "http")));
//        mysqlConnection = DriverManager.getConnection("jdbc:mysql://localhost:3306/logs", "username", "password");
//        logPatterns = loadLogPatternsFromMySQL();
    }

    public void start() throws IOException {
        byte[] buffer = new byte[BUFFER_SIZE];

        while (true) {
            DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
            socket.receive(packet);
            String logData = new String(packet.getData(), 0, packet.getLength(), StandardCharsets.UTF_8);
            processLog(logData);
        }
    }

    private void processLog(String logData) {
        System.out.println(logData);
        // 提取发送IP
//        InetAddress senderAddress = packet.getAddress();
//        String senderIp = senderAddress.getHostAddress();
//
//        // 根据发送IP获取资产类型
//        String assetType = getAssetTypeFromMySQL(senderIp);
        String assetType = "";

        // 根据资产类型获取解析规则
        Pattern logPattern = logPatterns.get(assetType);

        if (logPattern != null) {
            Matcher matcher = logPattern.matcher(logData);

            if (matcher.matches()) {
                // 解析日志字段
                String field1 = matcher.group(1);
                String field2 = matcher.group(2);
                // ... 解析更多字段

                // 构建要插入ES的文档
                Map<String, Object> document = new HashMap<>();
                document.put("field1", field1);
                document.put("field2", field2);
                // ... 添加更多字段

                // 插入ES
//                IndexRequest request = new IndexRequest("logs").source(document, XContentType.JSON);
//                esClient.index(request, RequestOptions.DEFAULT);
            }
        }
    }

    private Map<String, Pattern> loadLogPatternsFromMySQL() throws SQLException {
        Map<String, Pattern> logPatterns = new HashMap<>();

        String query = "SELECT asset_type, log_pattern FROM asset_logs";
        PreparedStatement statement = mysqlConnection.prepareStatement(query);
        ResultSet resultSet = statement.executeQuery();

        while (resultSet.next()) {
            String assetType = resultSet.getString("asset_type");
            String logPatternString = resultSet.getString("log_pattern");
            Pattern logPattern = Pattern.compile(logPatternString);
            logPatterns.put(assetType, logPattern);
        }

        return logPatterns;
    }

    private String getAssetTypeFromMySQL(String senderIp) throws SQLException {
        String query = "SELECT asset_type FROM assets WHERE ip = ?";
        PreparedStatement statement = mysqlConnection.prepareStatement(query);
        statement.setString(1, senderIp);
        ResultSet resultSet = statement.executeQuery();

        if (resultSet.next()) {
            return resultSet.getString("asset_type");
        }

        return null;
    }

    public static void main(String[] args) {
        try {
            LogReceiver receiver = new LogReceiver();
            receiver.start();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
